﻿#ifndef CONTROLLER_H
#define CONTROLLER_H

#include <QObject>
#include "protocol/serial.h"
#include "protocol/command.h"
#include "mc_config.h"
#include "utils/file_csv.h"

#define Q5_2_float(v) ((float)v / 32.0f)

#define R_TYPE   1
#define L_TYPE_D 2
#define L_TYPE_Q 3
#define FLUX_TYPE 4

class Controller : public QObject
{
    Q_OBJECT
public:
    explicit Controller(Serial *serial, int addr = 0x4d, QObject *parent = nullptr);
    ~Controller();
    bool StartRun(bool start);
    QStringList GetCtrlModes();
    bool setPoltIds(QList<int> &ids);
    Enum::EMode CtrlMode(QString s);
    bool SetCtrlMode(Enum::EMode);
    bool SetCtrlMode(QString s);
    bool SetTargetVelocity(int vel);
    bool SetTargetTorque(s16 torque);
    bool ForceRunning(float vd, float rpm);
    bool SetDqCurrent(s16 id, s16 iq);
    bool SetDqVoltage(u8 vd, u8 vq);
    bool GetVersion(QString &verion);
    int DeviceAddress(){
        return 0x4D;
    }
signals:
    void setPlotIdsSignal();
    void contrl_status(QString);
    void plotDataSingal(unsigned mask, float p1, float p2, float p3, float p4);
    void log_data_recved(int src, int dest, QString text);
private slots:
    void onFrameRecved(RxMessage &message);
private:
    void StatusProcess(RxMessage &message);
    float convertPlotData(int id, s16 v);
    bool write_config_command(Enum::ECommand cmd, u16 total_len, u16 offset, QByteArray &data);
    QByteArray *read_config_command(Enum::ECommand cmd, u16 offset, bool &finised);

    QList<int> plot_ids;
    Serial *serial;
    QThread *work_thread;
    int addr;
    int update_addr;
public:

    bool b_start;
    u8   gear;
    u32  life_time;
    Enum::EMode mode;
    QMap<QString, Enum::EMode> modes;
    float dq_current[2];
    float dq_voltage[2];
    int   temperature[2];
    int   rpm;
    float dc_voltage;
    float dc_current;
    u32  err_mask;
    u32  warn_mask;
    mc_config_t mc_conf;
    app_config_t app_conf;
};

#endif // CONTROLLER_H
